package com.lq.ecoldchain.ui.mine.carInfo.carline

import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.MutableLiveData
import android.view.LayoutInflater
import com.alibaba.android.arouter.launcher.ARouter
import com.lq.ecoldchain.R
import com.lq.ecoldchain.base.BaseNavigator
import com.lq.ecoldchain.base.view.App
import com.lq.ecoldchain.base.viewmodel.BaseViewModel
import com.lq.ecoldchain.entity.CityInfo
import com.lq.ecoldchain.internet.BaseObserver
import com.lq.ecoldchain.util.toast

/*
*2018/12/28 0028  17:00
*function by lq
*/
class CarLineViewModel:BaseViewModel(){
    val refreshing by lazy { MutableLiveData<Boolean>() }
    val list by lazy { ArrayList<CityInfo>() }
    val adapter by lazy { CarLineAdapter(list) }

    init {
        obtainCarAllLine()
        val view = LayoutInflater.from(App.instance).inflate(R.layout.layout_add_other,null)
        view.setOnClickListener {
            //添加路线
            ARouter.getInstance().build(BaseNavigator.cityAll).navigation()
        }
        adapter.addFooterView(view)
        adapter.setOnItemChildLongClickListener { _, _, position ->
            //删除该线路
            deleteItem(list[position].id)
            true
        }
    }

    fun refreshData(){
        refreshing.value = true
        obtainCarAllLine()
    }

    private fun deleteItem(id:Int){
        BaseNetCore.ApiServiceImpl.removeDriverRoute(id).compose(RxTransformer.switchSchedulers()).subscribe(object:BaseObserver<String>(){
            override fun onSuccess(t: String?) {
                toast { "删除成功" }
                refreshData()
            }

            override fun onFail(code: String) {
                toast { "删除失败" }
            }
        })
    }

    override fun onResume(lifecycleOwner: LifecycleOwner) {
        super.onResume(lifecycleOwner)
        obtainCarAllLine()
    }

    private fun obtainCarAllLine(){
        BaseNetCore.ApiServiceImpl.obtainCarAllLine().compose(RxTransformer.switchSchedulers()).subscribe(object:BaseObserver<List<CityInfo>>(){
            override fun onSuccess(t: List<CityInfo>?) {
                if(!t.isNullOrEmpty()){
                    list.clear()
                    list.addAll(t)
                    adapter.notifyDataSetChanged()
                }
                if(refreshing.value==true){
                    toast { "刷新成功" }
                }
                refreshing.value = false
            }

            override fun onFail(code: String) {
                if(refreshing.value==true){
                    toast { "刷新失败" }
                }
                refreshing.value = false
            }
        })
    }
}